<template lang="pug">
    div(@touchstart="touchstart",
        @touchmove="touchmove",
        @touchend ="touchend",
        class="touch-panel")  
      slot
</template>

<script>
import axios from 'axios'
export default {
    data(){
        return {
            partitions: [],
            touchstartInfo: null,
            touchstartTimestamp: null,
            touchendInfo: null,
            touchmoveTem: null,
            touchOrigin: null
        }
    },
    computed:{
        marginLeft(){
            let marginLeft = this.$el.style.marginLeft.replace(marginLeft, 'px')
            marginLeft = marginLeft ? parseInt(marginLeft) : 0;
            return marginLeft;
        }
    },
    methods:{
      touchstart({timeStamp, touches }){
          this.touchstartTimestamp = timeStamp
          this.touchmoveTem = touches[0]
          this.touchOrigin = touches[0]
      },
      touchend({timeStamp, changedTouches }){
          const touch = changedTouches[0]
          // 起始移动到结束的移动距离
          const moveDistance = touch.screenX - this.touchOrigin.screenX
          if(this.$el.offsetWidth / 2 > moveDistance) {
            // 移动没移动长度一半的距离，返回
            this.movePanelX(-moveDistance);
          }else{
            this.moveOut();
          }
      },
      touchmove({timeStamp, touches }){
          const touch = touches[0]
          const distance = touch.screenX - this.touchmoveTem.screenX
          
          this.movePanelX(distance); 

          this.touchmoveTem = touches[0]
      },
      /**
       * X轴移动
       */
      movePanelX(distanceX){
        let marginLeft = this.getMarginLeft();
        this.$el.style.marginLeft = marginLeft + distanceX + 'px'
      },
      getMarginLeft(){
        let marginLeft = this.$el.style.marginLeft.replace(marginLeft, 'px')
        marginLeft = marginLeft ? parseInt(marginLeft) : 0;
        return marginLeft;
      },
      moveOut(){
          let index = 0
          let timer = setInterval(function(){
            this.movePanelX(-20 + index * 10);
            if(this.getMarginLeft() <= -100) clearInterval(timer)
          }.bind(this), 20)
      }
    },
    created(){
      
    }
}
</script>

<style scoped>
.touch-panel{
    background-color: green
}
</style>
